package com.zhou.juc.test09_Interview;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouyanxiang
 * @create 2020-08-2020/8/15-13:32
 */
public class T04_NotifyFreeLock {

    volatile List lists = new ArrayList();

    public void add(Object o) {
        lists.add(o);
    }

    public int size() {
        return lists.size();
    }

    public static void main(String[] args) {
        T04_NotifyFreeLock t = new T04_NotifyFreeLock();
        final Object lock = new Object();

        new Thread(()->{
            synchronized (lock){
                System.out.println(Thread.currentThread().getName() + " start ...");
                    if (t.size() != 5) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                System.out.println(Thread.currentThread().getName() + " end...");
                lock.notify();
            }
        },"t2").start();

        new Thread(()->{
            System.out.println(Thread.currentThread().getName() + " start...");
            synchronized (lock){
                for (int i = 0; i < 10; i++) {
                    t.add(new Object());
                    System.out.println("add  " + i);
                    if (t.size() == 5){
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            System.out.println(Thread.currentThread().getName() + " end...");
        },"t1").start();
    }
}
